using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Emlyn.Applications.Scratch.Graphics.Tools;
using Microsoft.DirectX.Direct3D;

namespace Emlyn.Applications.Scratch.Graphics.Chapter4
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public DirectXWrapper _wrapper = null;

        public Bitmap _bitmap = null;

        public Surface _loadedImage = null;

        private void Form1_Load(object sender, EventArgs e)
        {
            InitWrapper();

//            _loadedImage = _wrapper.LoadSurfaceFromFile(@"X:\emlyn\images\palace tileset.bmp");

            _bitmap = new Bitmap(@"X:\emlyn\images\palace tileset.bmp");

            //_loadedImage.Disposing += new EventHandler(LIDisposing); 
         
            _wrapper._device.DeviceLost += new EventHandler(DeviceLostHandler);
        }

        private void DisposeWrapper()
        {
            if (_loadedImage != null && !_loadedImage.Disposed)
                _loadedImage.Dispose();
            if (_wrapper != null && _wrapper._backbuffer != null)
                _wrapper._backbuffer.Dispose();
        }

        private void InitWrapper()
        {
            DisposeWrapper();

            _wrapper = new DirectXWrapper(this.ClientSize.Width, this.ClientSize.Height, this);
        }

        private void LIDisposing(object sender, EventArgs e)
        {
            MessageBox.Show("Disposing");
        }

        private void DeviceLostHandler(object sender, EventArgs e)
        {
            InitWrapper();
        }

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            _wrapper.Clear(Color.Black);

            if ((_loadedImage == null) || (_loadedImage.Disposed == true))
                _loadedImage = _wrapper.LoadSurfaceFromBitmap(_bitmap);
                
            _wrapper.DrawOntoBackBuffer(
                _loadedImage,
                new Rectangle(
                    0, 0, 240, 268
                    ),
                new Point(
                    -25, -25
                    )
            );

            _wrapper.Present();
        }

        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape)
                Close();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            DisposeWrapper();
        }


    }
}